const {ChatModel} = require('./models')

module.exports = function (server) {
    var io = require('socket.io')(server, { cors: true });

    io.on('connection', (socket) => {
        console.log('a user connected',socket.id);
        socket.on("sendMessage", ({ from, to, content }) => {
            console.log("server 收到消息",{ from, to, content });
            const chat_id = [from, to].sort().join('_');
            const create_time = Date.now();
            const chatModel = new ChatModel({ chat_id, from, to, create_time, content })
            chatModel.save(function (err, chatMsg) {
                //保存完成后,向所有连接的客户端发送消息io.emit('receiveMessage',chatMsg)//全局发送,所有连接的客户端都可以收到
                io.emit("receiveMessage", chatMsg)
            })

        })
    });
}